<template>
  <div class="page-main" v-title data-title="物料领用">
    <home-nav :userData="userinfo"></home-nav>
    <div class="banner"><span>物料领用</span></div>
    <div class="container">
      <div class="head-content">
        <span class="bold-font">物料领用单详情</span>
        <div class="btn-line">
          <!-- <ArticleContent ref="ArticleContent" btnText="操作指引" articleNo="MaterialsTips"/> -->
          <a-button type="link" @click="openConsumTips()" >操作指引</a-button>
          <a-button icon="a-icon-files" type="primary" @click="handleSaveConsum(0)">保存</a-button>
          <!-- <a-button icon="a-icon-s-grid" @click="handleAuditConsum" plain v-if="consum.id">提交申请</a-button> -->
          <a-button v-if="consum.applyStatus != '4'" icon="a-icon-s-grid" @click="handleAsyncToSap" plain
            >生成SAP拣配单</a-button
          >
        </div>
      </div>
      <div class="app-container">
        <a-form-model
          ref="consum"
          :model="consum"
          :rules="rules"
          style="margin-top: 10px"
          label-width="160px"
          label-position="right"
        >
          <section>
            <div class="section-header">基础信息</div>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="申请单号:">
                  <a-input v-model="consum.consumNum" disabled placeholder="自动生成流水号" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申领人/部门:" prop="consumUser">
                  <a-input
                    :value="
                      (consum.applyUser ? consum.applyUser : '') +
                      '/' +
                      (consum.applyUserDept ? consum.applyUserDept : '')
                    "
                    disabled
                    placeholder="自动带入信息"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申领时间:">
                  <a-date-picker
                    disabled
                    style="width: 100%"
                    valueFormat="YYYY-MM-DD"
                    v-model="consum.consumTime"
                    placeholder="自动带入时间"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <div>
                  <a-form-model-item label="提货人:" prop="consumUser">
                    <div style="display: flex;justify-content: space-between;align-items: center;">
                      <a-input v-model="consum.consumUser" placeholder="姓名" :disabled="pageType == 'view'" />
                      <a-input v-model="consum.consumContact" placeholder="联系电话必填" :disabled="pageType == 'view'" />
                      <!-- <a-button type="link" @click="fillRemark" v-if="pageType != 'view'">填充</a-button> -->
                    </div>
                  </a-form-model-item>
                  <!-- <div style="text-align: right; color: #ccc">说明：点击填充可批量将提货人及联系方式填充到备注中。</div> -->
                </div>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="物料类型:" prop="materialsType" >
                  <div style="display: flex;justify-content: space-between;align-items: center;">
                  <a-radio-group
                    class="border-radio-group"
                    v-model="consum.materialsType"
                    @change="changeMaterialsType"
                  >
                    <a-radio
                      v-for="item in materialsTypeOptions"
                      :key="'materialsType' + item.code"
                      :value="item.code"
                      >{{ item.text }}</a-radio
                    >
                  </a-radio-group>

                  <!-- <a-button type="link" @click="openMaterialsTypeTips()" >说明</a-button> -->
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="费用号:" prop="costNum">
                  <div style="display: flex;justify-content: space-between;align-items: center;flex-wrap: wrap;">
                    <a-select
                      v-model="consum.costType"
                      @change="changeCostType"
                      placeholder="费用类型"
                      style="width: 93px;margin-right:2px"
                      :disabled="!consum.materialsType"
                    >
                      <template v-for="item in costTypeOptions">
                        <a-select-option
                          v-if="
                            (item.code == '1' && consum.materialsType != '2') ||
                            (item.code == '2' && consum.materialsType != '3')
                          "
                          :key="'costType' + item.code"
                          :value="item.code"
                        >
                          {{ item.text }}
                        </a-select-option>
                      </template>
                    </a-select>
                    <a-select
                      style="flex:1"
                      show-search
                      v-model="consum.costNum"
                      :default-active-first-option="false"
                      :show-arrow="false"
                      :filter-option="false"
                      :not-found-content="null"
                      allow-clear
                      @search="fetchCostNum"
                      @select="selectCostNum"
                      :disabled="pageType == 'view' || !consum.materialsType"
                      :dropdownMatchSelectWidth="false"
                      :dropdownStyle="{ width: consum.costType == '2' ? '600px !important' : '' }"
                    >
                      <a-select-option v-for="(d, index) in costNumList" :key="index">
                        <template v-if="consum.costType == '1'">
                          {{ d.costNumber }}
                        </template>
                        <template v-else> {{ d.costNumber }}/{{ d.projectName }}/{{ d.projectManager }} </template>
                      </a-select-option>
                    </a-select>
                    <a-button type="link" @click="openMaterialsSelector('2')" v-if="pageType != 'view'">获取</a-button>
                  </div>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="项目名称:" prop="projectName">
                  <a-input v-model="consum.projectName" disabled placeholder="若选WBS号，随WBS号带出" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目负责人:" prop="projectManager">
                  <a-input disabled v-model="consum.projectManager" placeholder="若选WBS号，随WBS号带出" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申领物料总价:" prop="applyTotalPrice">
                  <a-input v-model="consum.applyTotalPrice" disabled placeholder="自动计算所领物料总价" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="拣配单号:">
                  <a-input v-model="consum.jpno" disabled placeholder="生成至SAP后返回" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="领料说明:" prop="remark">
                  <a-input v-model="consum.remark" :disabled="pageType == 'view'" />
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <div>
                  <a-form-model-item label="采购计划号:">
                    <a-input
                      :disabled="pageType == 'view'"
                      v-model="consum.applyPlanNum"
                      allow-clear
                      readOnly
                      @change="clearPlanNum"
                      placeholder="从HIP采购需求计划获取物料号查询"
                    >
                      <a-icon slot="addonAfter" type="search" @click="openPlanNumSelector" v-if="pageType != 'view'" />
                    </a-input>
                  </a-form-model-item>
                  <div style="text-align: right; color: #ccc">说明：填入采购申请号，可针对采购物料进行领用。</div>
                </div>
              </a-col> -->
            </a-row>
          </section>
          <section>
            <div class="section-header" style="display: flex; justify-content: space-between">物料明细
              <div v-if="pageType != 'view'" class="btn-line">
                <a-button icon="a-icon-download" type="primary" @click="openMaterialsSelector('1')"
                  >获取库存数据</a-button
                >
                <a-button icon="a-icon-s-grid" @click="handleRemove" plain>删除</a-button>
              </div>  
            </div>            
            <a-table
            :scroll="{ x: 3000 }"
              class="hte-table-content"
              :columns="columns"
              :data-source="consum.items"
              :pagination="false"
              :rowKey="(record, index) => record.randomStr"
              :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
              :customRow="customRow"
              bordered
              size="small"
            >
              <template slot="materialsTypeRender" slot-scope="text, record">
                <template v-for="item in materialsTypeOptions">
                  <span v-if="item.code == record.materialsType" :key="item.code"> {{ item.text }}物资 </span>
                </template>
              </template>
              <template slot="bdmngRender" slot-scope="text, record">
                {{ record.bdmng }}
                <!-- <a-input v-model="record.bdmng" @change="changeBdmng(index)" /> -->
              </template>
              <template slot="remarkRender" slot-scope="text, record">
                <a-input v-model="record.remark" :disabled="pageType == 'view'" />
              </template>
              <template slot="sobkzRender" slot-scope="text, record">
                <div v-if="record.sobkz == '10'">Y</div>
              </template>
              <template slot="kostlRender" slot-scope="text, record">
                <span class="font-active" @click="toDetail('costCenter', record.kostl)"> {{ record.kostl }}</span>
              </template>
              <template slot="matnrRender" slot-scope="text, record">
                <span class="font-active" @click="toDetail('materialsNo', record.matnr)"> {{ record.matnr }}</span>
              </template>
              <template slot="posidRender" slot-scope="text, record">
                <span class="font-active" @click="toDetail('wbsNo', record.posid)"> {{ record.posid }}</span>
              </template>
              <template slot="applyUserDeptRender" slot-scope="">
                {{ consum.applyUserDept }}
              </template>
              <template slot="applyUserRender" slot-scope="">
                {{ consum.applyUserRender }}
              </template>
            </a-table>
          </section>
        </a-form-model>
        <PlanNumSelector ref="planNumSelector" @close="closePlanNumSelector" />
        <CostPowerSelector ref="costPowerSelector" @close="closeCostPowerSelector" />
        <MaterialsSelector ref="MaterialsSelector" @close="closeMaterialsSelector" />
      </div>
    </div>
    <ConsumTips ref="ConsumTips"/>
    <MaterialsTypeTips ref="MaterialsTypeTips"/>
   
  </div>
</template>
<script>
import MaterialsSelector from './MaterialsSelector'
import PlanNumSelector from './PlanNumSelector'
import CostPowerSelector from './CostPowerSelector'
import { postAction, getAction } from '@/api/manage'
import { ColumnWidthMixin } from '@/views/materials/ColumnWidthMixin'
import { CodesMixin } from '@/mixins/CodesMixin'
import  ConsumTips  from '@/views/materials/ConsumTips'
import  MaterialsTypeTips  from '@/views/materials/MaterialsTypeTips'
import { Modal } from 'ant-design-vue'
export default {
  inject: ['reload'],
  mixins: [ColumnWidthMixin,CodesMixin],
  name: 'MaterialsAddConsum',
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    ArticleContent: () => import('@/views/back/article/ArticleContent'),
    MaterialsSelector,
    PlanNumSelector,
    CostPowerSelector,
    ConsumTips,
    MaterialsTypeTips,
  },
  data() {
    return {
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractTaskList',
      },
      urls: {
        saveconsum: '/materials/edit',
        auditconsum: '/materials/audit',
        deleteItem: '/materials/deleteItem',
        getconsums: '/materials/getConsum',
        psCodes: '/hte/contract/codes',
        personList: '/person/info/personList',
        asyncToSap: '/materials/asyncToSap',
        fetchCostNum: '/materials/fetchCostNum',
      },
      activeNames: ['1', '2'], // 折叠面板默认打开的a-collapse-item name
      multipleSelection: [],
      consum: {
        applyTotalPrice: 0.0,
        materialsType: '',
        items: [],
        costType: '2',
      },
      costTypeOptions: [
        { code: '1', text: '成本中心' },
        { code: '2', text: 'WBS号' },
      ],
      materialsTypeOptions: [
        { code: '1', text: '预留' },
        { code: '2', text: 'WBS' },
        { code: '3', text: '公有' },
      ],
      dictMap: {},
      powers: {},
      rules: {
        // costNum: [{ required: true, message: "费用号", trigger: "change" }],
        // projectName: [
        //   { required: true, message: "项目名称", trigger: "change" },
        // ],
        // projectManager: [
        //   { required: true, message: "项目负责人", trigger: "change" },
        // ],
        consumUser: [{ required: true, message: '请选择申领人', trigger: 'change' }],
        consumContact: [{ required: true, message: '请输入联系电话', trigger: 'change' }],
        // remark: [{ required: true, message: '请输入领料说明', trigger: 'change' }],
        // applyTotalPrice: [{ required: true, message: '请输入申领物料总价', trigger: 'change' }],
        // bdmng: [{ required: true, message: '请输入领用数量', trigger: 'change' }],
        // consumTime: [{ required: true, message: '请输入申领时间', trigger: 'change' }],
      },
      maktxWidth: '120px',
      columns: [
        {
          title: '物料类型',
          dataIndex: 'materialsType',
          width: '100px',
          align: 'center',
          // scopedSlots: { customRender: 'materialsTypeRender' },
        },
        {
          title: '寄售标志',
          dataIndex: 'sobkz',
          width: '100px',
          align: 'center',
          scopedSlots: { customRender: 'sobkzRender' },
        },
        {
          title: '拣配单号',
          dataIndex: 'jpno',
          width: '140px',
          align: 'center',
        },
        {
          title: '配送单号',
          dataIndex: 'psno',
          width: '140px',
          align: 'center',
        },
        {
          title: '物料编码',
          dataIndex: 'matnr',
          width: '120px',
          align: 'center',
          scopedSlots: { customRender: 'matnrRender' },
        },
        {
          title: '物料名称',
          dataIndex: 'maktx',
          width: '120px',
          align: 'left',
          customCell: () => {
            return {
              style: {
                width: this.maktxWidth,
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                cursor: 'pointer',
              },
            }
          },
          customRender: (text, record) => (
            <a-tooltip placement="topLeft" title={record.maktx}>
              {record.maktx}
            </a-tooltip>
          ),
        },
        {
          title: '单位',
          dataIndex: 'meins',
          width: '60px',
          align: 'center',
        },
        {
          title: '领用数量',
          dataIndex: 'bdmng',
          width: '100px',
          align: 'center',
          scopedSlots: { customRender: 'bdmngRender' },
        },
        {
          title: '领用金额',
          dataIndex: 'totalPrice',
          width: '100px',
          align: 'center',
        },
        // {
        //   title: '移动单价',
        //   dataIndex: 'price',
        //   width: '100px',
        //   align: 'center',
        // },
        {
          title: '收货方',
          dataIndex: 'wempf',
          width: '100px',
          align: 'center',
        },
        // {
        //   title: '项目负责人',
        //   dataIndex: 'projectManager',
        //   width: '120px',
        //   align: 'center',
        // },
        // {
        //   title: '是否急用',
        //   dataIndex: 'isUrgent',
        //   width: '100px',
        //   align: 'center',
        // },
        {
          title: '备注',
          dataIndex: 'remark',
          width: '100px',
          align: 'center',
          scopedSlots: { customRender: 'remarkRender' },
        },
        {
          title: '可用库存',
          dataIndex: 'lessNum',
          width: '100px',
          align: 'center',
        },
        {
          title: '预留数量',
          dataIndex: 'reserveNum',
          width: '100px',
          align: 'center',
        },
        {
          title: '提货数量',
          dataIndex: 'ENMNG',
          width: '100px',
          align: 'center',
        },
        {
          title: '库存总数',
          dataIndex: 'stockNumTotal',
          width: '100px',
          align: 'center',
        },
        {
          title: '成本中心',
          dataIndex: 'kostl',
          width: '140px',
          align: 'center',
          scopedSlots: { customRender: 'kostlRender' },
        },
        {
          title: 'WBS元素',
          dataIndex: 'posid',
          width: '140px',
          align: 'center',
          scopedSlots: { customRender: 'posidRender' },
        },
        {
          title: '需求部门',
          dataIndex: 'KTEXT',
          width: '100px',
          align: 'center',
          scopedSlots: { customRender: 'applyUserDeptRender' },
        },
        {
          title: '订单下达人',
          dataIndex: 'createOrderUser',
          width: '120px',
          align: 'center',
          scopedSlots: { customRender: 'applyUserRender' },
        },
        {
          title: '预留单号',
          dataIndex: 'RSNUM',
          width: '100px',
          align: 'center',
        },
        {
          title: '预留单项目号',
          dataIndex: 'RSPOS',
          width: '120px',
          align: 'center',
        },

        {
          title: '库存地点',
          dataIndex: 'lgort',
          width: '100px',
          align: 'center',
        },
      ],
      pageType: 'add',
      records: [],
      selectedRowKeys: [],
      selectedRow: [],
      selectCostNumTimeOut: null,
      selectCostNumKeyWord: null,
      costNumList: [],
    }
  },

  created() {
    this.fetchCodes([
      '五金领料-操作指引'
    ])
    if (this.$route.path.startsWith('/materials/add')) {
      this.pageType = 'add'
    }
    if (this.$route.path.startsWith('/materials/edit')) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
      this.pageType = 'edit'
    }
    if (this.$route.path.startsWith('/materials/view')) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
      this.pageType = 'view'
    }
  },
  computed: {},
  methods: {
    fetchData(id) {
      getAction(this.urls.getconsums + '/' + id).then((res) => {
        if (res.code == 200) {
          this.consum = res.data
          if (this.consum.consumStatus > 0) {
            this.pageType = 'view'
          }
        } else {
          this.$message.error('获取数据失败')
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    appendRecords(records) {
      if (records) {
        // if (!this.consum.items) {
        //   this.consum.items = []
        // }
        // let materialsNos = []
        // let items = this.consum.items
        // items.forEach((i) => {
        //   materialsNos.push(i.cmtno)
        // })

        // data.forEach((d) => {
        //   if (materialsNos.indexOf(d.cmtno) <0) {
        //     items.push(d)
        //   }
        // })
        // this.consum.items = items
        let items = this.consum.items
        let newItems = []
        records.forEach((r) => {
          let isNewItem = true
          items.forEach((i) => {
            if (r.matnr == i.matnr && r.wempf == i.wempf) {
              i.bdmng = r.bdmng
              i.totalPrice = r.totalPrice
              isNewItem = false
            }
          })
          if (isNewItem) {
            r.createOrderUser = this.userinfo.info.realname
            r.createOrderUserId = this.userinfo.info.username
            items.push(r)
          }
        })
        this.$set(this.consum, 'items', items)
        this.countTotalPrice()
        this.columns = this.calcMaktxWidth(this.consum.items, this.columns, ['maktx', 'wempf'])
      }
    },
    async handleSaveConsum(type = 0) {
      let check = false
      this.$refs['consum'].validate((valid) => {
        if (valid) {
          check = true
        }
      })
      if (!check) {
        return
      }
      let items = this.consum.items
      if (!items || items.length <= 0) {
        return this.$message.warning('请选择至少一条数据生成拣配单')
      }
      let i = 1
      for (let item of items) {
        if (!item.remark) {
          return this.$message.warning('请输入第【' + i + '】行备注')
        }
        if (!item.bdmng || item.bdmng == 0) {
          return this.$message.warning('请输入第【' + i + '】行领用数量')
        }
        i++
      }
      let res = await postAction(this.urls.saveconsum, this.consum)
      if (res.success) {
        this.consum = res.result
        this.$message.success('保存成功')
        if (type == 0) {
          this.$router.push('/materials/editConsum/' + this.consum.id)
        } else {
          return true
        }
      } else {
        this.$message.error('保存失败,' + res.message)
      }
    },
    handleAsyncToSap() {
      if (this.handleSaveConsum('1')) {
        getAction(this.urls.asyncToSap + '?id=' + this.consum.id).then((res) => {
          if (res.success) {
            this.$message.success('生成SAP拣配单成功')
            this.$router.push('/materials/editConsum/' + this.consum.id)
          } else {
            this.$message.error('生成SAP拣配单失败:' + res.message)
          }
        })
      }
    },
    handleAuditConsum() {
      let check = false
      this.$refs['consum'].validate((valid) => {
        if (valid) {
          check = true
        }
      })
      if (!check) {
        return
      }
      getAction(this.urls.auditconsum + '/' + this.consum.id).then((res) => {
        if (res.code == 200) {
          this.consum = res.data
          this.$message.success('提交成功')
        } else {
          this.$message.error('提交失败,' + res.msg)
        }
      })
    },
    changeBdmng(index) {
      let bdmng = this.consum.items[index].bdmng
      if (bdmng) {
        bdmng = bdmng.trim()
      } else {
        bdmng = 0
      }
      while (bdmng.length > 1 && bdmng.startsWith('0')) {
        bdmng = bdmng.substring(1, bdmng.length)
      }
      this.$set(this.consum.items[index], 'bdmng', bdmng)
      if (isNaN(this.consum.items[index].bdmng)) {
        this.$set(this.consum.items[index], 'bdmng', 0)
      }
      if (this.records[index].sobkz == '10') {
        if (this.records[index].bdmng > this.records[index].noReserveNum) {
          this.$set(this.records[index], 'bdmng', this.records[index].noReserveNum)
        }
      } else {
        if (this.records[index].bdmng > this.records[index].lessNum) {
          this.$set(this.records[index], 'bdmng', this.records[index].lessNum)
        }
      }
      if (this.consum.items[index].bdmng < 0) {
        this.$set(this.consum.items[index], 'bdmng', 0)
      }
      this.$set(
        this.consum.items[index],
        'totalPrice',
        (this.consum.items[index].price * this.consum.items[index].bdmng).toFixed(3)
      )
      this.countTotalPrice()
    },
    fetchCode() {
      postAction(this.urls.psCodes, { codes: [] }).then((res) => {
        if (res.success) {
          this.dictMap = res.result
        }
      })
    },

    openPlanNumSelector() {
      this.$refs.planNumSelector.open()
    },
    closePlanNumSelector(data) {
      if (data) {
        this.$set(this.consum, 'applyPlanId', data.id)
        this.$set(this.consum, 'applyPlanNum', data.planNum)
        this.$set(this.consum, 'costNum', null)
        this.$set(this.consum, 'costType', null)
        this.$set(this.consum, 'projectName', null)
        this.$set(this.consum, 'projectManager', null)
      }
    },
    clearapplyPlanNum() {
      this.$set(this.consum, 'applyPlanId', null)
      this.$set(this.consum, 'applyPlanNum', null)
    },
    changeMaterialsType(val) {
      // this.$set(this.consum, 'items', [])
      // this.$set(this.consum, 'applyTotalPrice', 0.0)
      this.clearapplyPlanNum()
      this.$set(this.consum, 'items', [])
      this.$set(this.consum, 'applyTotalPrice', 0)
      this.$set(this.consum, 'costNum', null)
      this.$set(this.consum, 'costType', null)
      if (this.consum.materialsType == '1' || this.consum.materialsType == '3') {
        this.$set(this.consum, 'costType', '1')
      }
      if (this.consum.materialsType == '2') {
        this.$set(this.consum, 'costType', '2')
      }
    },
    changeCostType() {
      this.costNumList = []
      this.$set(this.consum, 'costNum', null)
      this.$set(this.consum, 'applyPlanId', null)
      this.$set(this.consum, 'applyPlanNum', null)
      this.$set(this.consum, 'projectName', null)
      this.$set(this.consum, 'projectManager', null)
      // this.$set(this.consum, 'items', [])
      // this.$set(this.consum, 'applyTotalPrice', 0)
    },
    openCostPowerSelector() {
      if (!this.consum.costType) {
        return this.$message.warning('请先选择费用类型')
      }
      this.$refs.costPowerSelector.doSelect(this.consum.costType)
    },
    closeCostPowerSelector(data) {
      console.info(data)
      if (data) {
        this.$set(this.consum, 'costNum', data.costNumber)
        if (this.consum.costType == '2') {
          this.$set(this.consum, 'projectName', data.projectName)
          this.$set(this.consum, 'projectManager', data.projectManager)
          this.$set(this.consum, 'projectManagerId', data.projectManagerId)
        }
      }
    },
    openMaterialsSelector(type) {
      if (type == '2') {
        if (!this.consum.costNum) {
          return this.$message.warning('请先选择费用号')
        }
      }
      if (!this.consum.consumUser) {
        return this.$message.warning('请先填写提货人信息')
      }
      if (!this.consum.consumContact) {
        return this.$message.warning('请先填写提货人联系电话')
      }
      if (type == '1') {
        if (!this.consum.costNum && !this.consum.applyPlanId) {
          return this.$message.warning('请先选择费用号或采购计划')
        }
      }
      this.$refs.MaterialsSelector.openInit(this.consum)
    },
    closeMaterialsSelector(data) {
      data.forEach((d) => {
        if (this.consum.consumContact) {
          d.remark = this.consum.consumUser + '/' + this.consum.consumContact
        } else {
          d.remark = this.consum.consumUser
        }
        if (this.consum.materialsType == '3') {
          d.kostl = this.consum.costNum
        }
      })
      this.appendRecords(data)
    },
    countTotalPrice() {
      let totalPrice = 0.0
      this.consum.items.forEach((item) => {
        item.totalPrice = 0.0
        if (item.bdmng) {
          item.totalPrice = parseFloat((item.bdmng * item.price).toFixed(3))
        }
        totalPrice = totalPrice + parseFloat(item.totalPrice)
      })
      this.consum.applyTotalPrice = totalPrice.toFixed(3)
    },
    customRow(record) {
      return {
        on: {
          dblclick: (event) => {
            let newRows = []
            let exist = false
            this.selectedRowKeys.forEach((k) => {
              if (k != record.randomStr) {
                newRows.push(k)
              } else {
                exist = true
              }
            })
            if (!exist) {
              newRows.push(record.randomStr)
            }
            this.selectedRowKeys = newRows
          },
        },
      }
    },
    toDetail(type, no) {
      let urlJump = this.$router.resolve({ path:'/materials/detail/' + type + '/' + no})
      window.open(urlJump.href, '_blank')
    },
    onSelectChange(selectedRowKeys, selectedRow) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRow = selectedRow
    },
    async handleRemove() {
      let that = this
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        Modal.confirm({
          title: '确认删除',
          content: '此操作将删除选中的记录, 是否继续?',
          onOk: function () {
            that.confirmRemove()
          },
        })
      } else {
        this.$message.warning('请至少选择一条记录进行操作')
      }
    },
    async confirmRemove() {
      let items = this.consum.items
      let newItems = []
      let removeIds = []
      items.forEach((i) => {
        if (i.id) {
          removeIds.push(i.id)
        }
      })
      let canMove = true
      if (removeIds && removeIds.length > 0) {
        let res = await postAction(this.urls.deleteItem, removeIds)
        if (res.success) {
          canMove = true
        } else {
          canMove = false
        }
      }
      if (canMove) {
        items.forEach((i) => {
          if (this.selectedRowKeys.indexOf(i.randomStr) < 0) {
            newItems.push(i)
          }
        })
        this.$message.success('移除成功')
      }
      this.selectedRowKeys = []
      this.selectedRow = []
      this.$set(this.consum, 'items', newItems)
    },
    clearPlanNum(planNum) {
      if (!planNum) {
        this.$set(this.consum, 'applyPlanId', null)
        this.$set(this.consum, 'applyPlanNum', null)
      }
    },
    fillRemark() {
      if (this.consum.consumUser) {
        if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
          let items = this.consum.items
          items.forEach((r) => {
            if (this.selectedRowKeys.indexOf(r.randomStr) > -1) {
              if (this.consum.consumContact) {
                r.remark = this.consum.consumUser + '/' + this.consum.consumContact
              } else {
                r.remark = this.consum.consumUser
              }
            }
          })
          this.$set(this.consum, 'items', items)
          this.$message.success('填充成功')
        } else {
          this.$message.warning('请至少选择一条记录进行操作')
        }
      } else {
        this.$message.warning('请选输入提货人')
      }
    },
    fillKostl() {
      if (this.consum.costNum) {
        if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
          let items = this.consum.items
          items.forEach((r) => {
            if (this.selectedRowKeys.indexOf(r.randomStr) > -1) {
              r.kostl = this.consum.costNum
            }
          })
          this.$set(this.consum, 'items', items)
          this.$message.success('填充成功')
        } else {
          this.$message.warning('请至少选择一条记录进行操作')
        }
      } else {
        this.$message.warning('请选择成本中心号')
      }
    },
    fetchCostNum(value) {
      if (!value) {
        return
      }
      if (this.selectCostNumTimeOut) {
        window.clearTimeout(this.selectCostNumTimeOut)
      }
      this.selectCostNumTimeOut = window.setTimeout(this.toFetchUserList, 800)
      this.selectCostNumKeyWord = value
    },
    selectCostNum(index) {
      let item = this.costNumList[index]
      this.closeCostPowerSelector(item)
    },
    async toFetchUserList() {
      let param = {}
      param.keyword = this.selectCostNumKeyWord
      ;(param.pageSize = 100), (param.costType = this.consum.costType)
      let res = await postAction(this.urls.fetchCostNum, param)
      if (res.success) {
        this.costNumList = res.result.records
      }
    },
    getRandomStr(len) {
      len = len || 32
      var $chars =
        'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      var maxPos = $chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    openConsumTips(){
      if(this.codes['五金领料-操作指引'] && this.codes['五金领料-操作指引'].length>0 ){
        this.windowOpen(this.codes['五金领料-操作指引'][0].parentid)
      }else{
        this.$message("请联系IT在数据字典添加【五金领料-操作指引】配置")
      }
      
    },
    openMaterialsTypeTips(){
      this.$refs.MaterialsTypeTips.openInit()
    }
  },
}
</script>

<style scoped>
.demo-table-expand .a-form-model-item {
  margin-right: 0;
  margin-bottom: 0px;
}
.demo-table-expand span {
  display: inline-block;
  white-space: nowrap;
  width: 95%;
  overflow: hidden;
  text-overflow: ellipsis;
}

.a-form-model-item >>> .a-form-model-item--mini .a-form-model-item__label {
  color: #606266 !important;
  font-size: 12px !important;
  font-weight: normal;
}
.a-table >>> .a-table__expanded-cell[class*='cell'] {
  padding: 0px 0px 10px 0px;
}

.expand-title {
  height: 30px;
  line-height: 30px;
  background-color: #f1f1f1;
  padding-left: 50px;
  margin-bottom: 5px;
  font-size: 12px;
}
.a-form-model-item >>> .a-form-model-item__content {
  height: 36px;
}
.ellipse-tooltips {
  display: inline-block;
  white-space: nowrap;
  width: 95%;
  overflow: hidden;
  text-overflow: ellipsis;
}
.ellipse-tooltips span {
  width: unset !important;
}
.a-range >>> .a-range-separator {
  width: 20px;
}
.searchForm {
  display: flex;
  flex-direction: row;
}
.searchForm-left {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  width: 85vw;
}
.searchForm-right {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  min-width: 280px;
  border-left: #cccccc 2px solid;
}
</style>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
.page-main {
  .banner {
    background-image: url(~@assets/contract-top.png);
  }
  .container {
    .content-list {
      margin-top: 15px;
    }
  }
  .font-active {
    cursor: pointer;
  }
}
.costNumClass0 {
}
.costNumClass1 {
}
/deep/.ant-select-dropdown {
  width: 400px !important;
}
/deep/.ant-form-item-control-wrapper{
  display: grid !important;
  align-items: center;
}
</style>
